<?php
/*
*用户模块
*/
class Adminuser_model extends CI_Model{
	public function __construct(){
		$this->load->database();
		
	}
	
//////////////单个用户////////////////////	

	//用户信息 , 角色信息 及其他
	public function userInfo($data){
		$this->db->select('id,username,email,role_id,status');
		if($query = $this->db->get_where('admin_user',$data)){
			return $query->row_array();
		}
		else{
			return false;
		}
	
	}


//////////////////////用户读写操作

	/**
	* 列出所用用户
	* $s:start $l: limit
	*/
	public function userList($s = 0, $l = 10){
		$this->db->select('r.name role_name,u.*');
		$this->db->from('admin_user u');
		$this->db->join('admin_role r','u.role_id=r.id','left');
		$this->db->limit($s,$l);
		$query = $this->db->get();
		return $query->result_array();
	}
	
	//添加用户
	//$name,$password,$email,$role_id
	public function addUser($data){
		
		return $this->db->insert('admin_user',$data);
	}
	
	//编辑用户
	public function editUser($data,$id){
		$this->db->where('id',$id);
		return $this->db->update('admin_user',$data);
	}
	
	//更新状态
	public function up_status($id,$status){
		
		$ids = explode(',',$id);
		$this->db->where_in('id',$ids);
		$this->db->update('admin_user',$status);
		//Q: how to get the real affected_rows and the object
		//怎么获得受影响的行数以及具体行的信息
		if($this->db->affected_rows() > 0){
			return true;
		}else{
			return false;
		}
	}
	
	//删除用户
	public function deleteUser($id){
		
		//删除
		$ids = explode(',',$id);
		$this->db->where_in('id',$ids);
		$this->db->delete('admin_user');
		$rows = $this->db->affected_rows();
		if($rows >= 1){
			return true;
		}else{
			return false;
		}

	}
	
	//用户权限
	public function userAction(){
	
	}
	
	//检测用户登录
	public function islogin(){
		$this->load->library('session');
		$username = $this->session->userdata('username');
		$actions = $this->session->userdata('actions');
	
		if( ! $username || ! $actions){
			return false;
		}
		return true;
	}
	
	
	//检测超管
	public function isadmin(){
		
	}
		
	//登录
	public function login($username,$password){
		$this->load->library('session');
		
		$data = array(
			'username' => $username,
			'password' => $password
		);
	
		//获得用户基本信息
		if( $userinfo = $this->userInfo($data) ){
			
			//获得用户角色权限
			
			//超管 具有所有权限
			if($userinfo['role_id'] == 1){
				$userinfo['actions']='all_allow';
				
			//其他角色
			}else{
			
				$this->db->select('action_list actions');
				$query = $this->db->get_where('admin_role',array('id'=>$userinfo['role_id']));
				$action = $query->row_array();
				
				$userinfo['actions'] = explode(',',$action['actions']);
			}
			$this->session->set_userdata($userinfo);
			return true;
		}else{
			return false;
		}
		
	} 
	
}